package com.cy.controller.interceptor;

import com.cy.annotation.LoginRequired;
import com.cy.util.HostHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @Author: cy
 * @Date: 2022/01/03/13:27
 * @Description:
 */
@Component
public class LoginRequiredInterceptor implements HandlerInterceptor {

    @Resource
    private HostHolder hostHolder;


    /**
     * 登录拦截器，只拦截方法, 用于禁止用户没有登录访问一些资源
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;  //判断是否是拦截方法
            Method method = handlerMethod.getMethod();     //获取拦截到的方法
            LoginRequired loginRequired = method.getAnnotation(LoginRequired.class);    //找到带登录拦截的注解
            if(loginRequired != null && hostHolder.getUser() == null){
                //假如有必须登录的注解，但是又没有登录,重定向到登录页面
                response.sendRedirect(request.getContextPath() + "/login");
                return false;
            }
        }
        return true;
    }
}
